const debounce = require('../../utils/debounce.js');
import http from '../../utils/http.js'
const apiConfig = require('../../utils/apiConfig.js')


Page({
  data: {
    page: 1,
    per_page: 10,
    hasMore: true,
    date: '',
    keyword: '',
    orderList: [],
    loading: false,
    customer_id: '',
    customer_name: '',
    searchTimer: null,
    customers: [],
    currentCustomerPage: 1,
    totalCustomerPages: 1,
    isLoadingCustomer: false,
    searchQueryCustomer: ''
  },

  onLoad() {
    this.loadData();
  },

  bindDateChange(e) {
    this.setData({
      date: e.detail.value,
      page: 1,
      hasMore: true,
      customer_id: '',
      customer_name: '',
      orderList: [],
      currentCustomerPage: 1,
      totalCustomerPages: 1,
      searchQueryCustomer: ''
    }, () => this.loadData())
  },

  searchOrders() {
    wx.showLoading({title: '搜索中'});
    setTimeout(() => {
      const filtered = this.data.orderList.filter(item => 
        item.address.includes(this.data.keyword)
      );
      wx.hideLoading();
      this.setData({orderList: filtered});
      if(filtered.length === 0) {
        wx.showToast({title: '未找到相关订单', icon: 'none'});
      }
    }, 500);
  },

  loadMore() {
    if (!this.data.hasMore || this.data.loading) return
    this.setData({
      page: this.data.page + 1
    })
    this.loadData()
  },

  loadData() {
    const that = this
    this.setData({ loading: true })
    http.request({
      url: apiConfig.getDeliveryList,
      method: 'GET',
      data: {
        page: this.data.page,
        per_page: this.data.per_page,
        now_date: this.data.date,
        customer_id: this.data.customer_id
      }
    }).then(res => {
      if (res.status == 200) {
        const adaptedData = res.data.map(item => ({
          ...item,
          orderNumber: item.id,
          driver: item.customer?.customer_name,
          goods_name: item.goods?.goods_name,
          num: item.num,
          total_price: item.total_price,
          formattedDate: that.formatDate(item.now_date)
        }))
        
        that.setData({
          orderList: that.data.page === 1 ? adaptedData : [...that.data.orderList, ...adaptedData],
          hasMore: adaptedData.length >= that.data.per_page
        })
      } else {
        that.setData({ orderList: [] });
      }
    })
    that.setData({ loading: false })
  },

  formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
  },

  viewDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/delivery-detail/delivery-detail?id=${id}`
    });
  },

  showActionSheet(e) {
    wx.showActionSheet({
      itemList: ['复制订单号', '标记异常'],
      success: (res) => {
        if(res.tapIndex === 0) {
          const orderNumber = this.data.orderList.find(
            item => item.id === e.currentTarget.dataset.id
          ).orderNumber;
          wx.setClipboardData({data: orderNumber});
        }
      }
    });
  },

  handleCustomerSearch: debounce(function(e) {
    const searchQueryCustomer = e.detail.value;
    this.setData({ searchQueryCustomer: searchQueryCustomer }, () => {
      this.setData({ currentCustomerPage: 1 }, () => this.loadCustomers())
    });
  }, 300),

  loadCustomers() {
    const that = this;
    this.setData({ isLoadingCustomer: true });
    http.request({
      url: apiConfig.getCustomerList,
      method: 'GET',
      data: {
        page: this.data.currentCustomerPage,
        per_page: 10,
        customer_name: this.data.searchQueryCustomer
      }
    }).then(res => {
      if (res.status == 200) {
        const newCustomers = res.data.data;
        that.setData({
          customers: that.data.currentCustomerPage === 1? newCustomers : [...that.data.customers,...newCustomers],
          totalCustomerPages: res.data.last_page
        });
      }else {
        that.setData({ customers: [] });
      }
    })
    that.setData({ isLoadingCustomer: false });
  },

  bindCustomerChange(e) {
    const selectedCustomer = this.data.customers[e.detail.value];
    this.setData({
      customer_id: selectedCustomer.id,
      customer_name: selectedCustomer.customer_name,
      page: 1,
      hasMore: true,
      orderList: []
    }, () => this.loadData())
  }
});